package com.sumfun.blog.utils;

import com.sumfun.blog.common.ErrorCode;
import com.sumfun.blog.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 登录相关工具类
 *
 * @author sumfun
 */
@Component
public class LoginUtils {

    private static RedisTemplate<String, String> redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        LoginUtils.redisTemplate = redisTemplate;
    }


    public static final String TOKEN_PREFIX = "token:";

    /**
     * 检查用户是否已登录
     *
     * @param request HTTP请求
     * @return 是否已登录
     */
    public boolean isLogin(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }

        String userAccount = redisTemplate.opsForValue().get(TOKEN_PREFIX + token);
        if (userAccount == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return true;
    }
}